package nio2;


import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class NIO2Server extends Thread {
    public void run() {
        try (AsynchronousServerSocketChannel serverSock = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(InetAddress.getLocalHost(), 8421));) {
            serverSock.accept(serverSock, new CompletionHandler<AsynchronousSocketChannel, AsynchronousServerSocketChannel>() {
                @Override
                public void completed(AsynchronousSocketChannel sockChannel, AsynchronousServerSocketChannel attachment) {
                    //serverSock.accept(serverSock, this);

                    sockChannel.write(Charset.defaultCharset().encode
                            ("Hello World!"));
                }

                @Override
                public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }


    }



    public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {
        NIO2Server server = new NIO2Server();
        server.start();
        Thread.sleep(10000);
        try (AsynchronousSocketChannel client = AsynchronousSocketChannel.open()) {
            client.bind(new InetSocketAddress(InetAddress.getLocalHost(), 8421));
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            for (;;) {
                Future<Integer> future = client.read(buffer);
                if (future.get() <= 0) { break; }
            }
            System.out.println(new String(buffer.array()));
//            byte[] bytes = new byte[4096];
//            client.read(ByteBuffer.wrap(bytes));
//            System.out.println(new String(bytes));



        }
    }
}
